package com.hvgroup.modules.sanic.web;


import com.hvgroup.modules.sanic.domain.dto.KnowledgeBase;
import com.hvgroup.modules.sanic.domain.dto.KnowledgeBaseItem;
import com.hvgroup.modules.sanic.service.DifyKBService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 知识库相关接口控制器
 */
@RestController
@RequestMapping("/api/kb")
@RequiredArgsConstructor
public class KnowledgeBaseController {

    private final DifyKBService knowledgeService;

    /**
     * 创建新的知识库
     *
     * @param request 创建请求参数
     * @return 新知识库 ID
     */
    @PostMapping
    public ResponseEntity<String> createKnowledgeBase(@RequestBody KnowledgeBase request) {
        String id = knowledgeService.createDatasets(request);
        return ResponseEntity.ok(id);
    }

    /**
     * 获取所有知识库列表
     *
     * @return 知识库信息列表
     */
    @GetMapping
    public ResponseEntity<List<KnowledgeBaseItem>> listKnowledgeBases(@RequestParam(required = false, defaultValue = "1") String page) {
        List<KnowledgeBaseItem> list = knowledgeService.listDatasets(page);
        return ResponseEntity.ok(list);
    }

    /**
     * 向知识库中上传文件
     *
     * @param id   知识库ID
     * @param file 文件对象
     * @return 成功或失败
     */
    @PostMapping("/{id}/upload")
    public ResponseEntity<Void> uploadFile(@PathVariable String id,
                                           @RequestParam("file") MultipartFile file) {
        knowledgeService.uploadFileToDatasets(id, file);
        return ResponseEntity.ok().build();
    }

    /**
     * 更新某个知识库信息
     *
     * @param id      知识库ID
     * @param request 更新请求
     * @return 成功
     */
    @PatchMapping("/{id}")
    public ResponseEntity<Void> updateKnowledgeBase(@PathVariable String id,
                                                    @RequestBody KnowledgeBaseItem request) {
        knowledgeService.updateKnowledgeBase(id, request);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除某个知识库
     *
     * @param id 知识库ID
     * @return 成功
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteKnowledgeBase(@PathVariable String id) {
        knowledgeService.deleteDatasets(id);
        return ResponseEntity.ok().build();
    }
}
